package com.suyunyou.manager.service;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.suyunyou.manager.dao.PageInfoDao;
import com.suyunyou.manager.pojo.PageInfo;
import com.system.comm.model.Page;
import com.system.comm.utils.FrameTimeUtil;
import com.system.handle.model.ResponseCode;
import com.system.handle.model.ResponseFrame;

/**
 * 提取到的页面的内容的Service
 * @author yuejing
 * @date 2016年6月26日 上午8:31:45
 * @version V1.0.0
 */
@Component
public class PageInfoService {

	private static final Logger LOGGER = Logger.getLogger(PageInfoService.class);
	@Autowired
	private PageInfoDao pageInfoDao;
	
	/**
	 * 新增提取记录
	 * @param siteId
	 * @param title
	 * @param content
	 * @param html
	 * @param author
	 * @param spiderUrl
	 */
	public void save(Integer siteId, String title, String content, String html, String author, String spiderUrl) {
		PageInfo org = getSpiderUrl(spiderUrl);
		if(org == null) {
			try {
				pageInfoDao.save(new PageInfo(siteId, title, content, html, author, spiderUrl));
			} catch (Exception e) {
				LOGGER.error("保存页面出现异常: " + e.getMessage());
			}
		}
	}

	/**
	 * 根据爬取地址获取对象
	 * @param spiderUrl
	 * @return
	 */
	private PageInfo getSpiderUrl(String spiderUrl) {
		return pageInfoDao.getSpiderUrl(spiderUrl);
	}

	public void delete(Integer pageId) {
		pageInfoDao.delete(pageId);
	}

	public ResponseFrame pageQuery(PageInfo pageInfo) {
		pageInfo.setDefPageSize();
		ResponseFrame frame = new ResponseFrame();
		if (pageInfo.getSpiderTime() != null) {
			pageInfo.setBeginTime(FrameTimeUtil.parseDate(FrameTimeUtil.parseString(pageInfo.getSpiderTime())));
			pageInfo.setEndTime(FrameTimeUtil.parseDate(FrameTimeUtil.parseString(pageInfo.getSpiderTime(), FrameTimeUtil.FMT_YYYY_MM_DD) + " 23:59:59"));
		}
		int total = pageInfoDao.findPageInfoCount(pageInfo);
		List<PageInfo> data = null;
		if(total > 0) {
			data = pageInfoDao.findPageInfo(pageInfo);
		}
		Page<PageInfo> page = new Page<PageInfo>(pageInfo.getPage(), pageInfo.getSize(), total, data);
		frame.setBody(page);
		frame.setCode(ResponseCode.SUCC.getCode());
		return frame;
	}

	public PageInfo getDtl(Integer pageId) {
		PageInfo pageInfo = pageInfoDao.getDtl(pageId);
		return pageInfo;
	}

}